package logic

import (
	"context"
	"errors"
	"newuser/modles/cache"
	"newuser/modles/mysql"
	"newuser/pkg"
	"newuser/userrpc/internal/svc"
	"newuser/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *userrpc.LoginRequest) (*userrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, err := cache.Rdb.Get(l.ctx, "captcha"+in.Phone).Result()
	if result != in.CaptchaImage {
		return nil, errors.New("图形验证码错误")
	}
	result1, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Phone).Result()
	if result1 != in.SendSmsCode {
		return nil, errors.New("短信验证码错误")
	}
	user := &mysql.User{
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	err = user.FirstUserByPhone(mysql.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码错误")
	}

	return &userrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
